package com.zanglikun;
import org.zeromq.ZContext;
import org.zeromq.ZMQ;
import org.zeromq.ZMQ.Socket;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
/**
 * @author : zanglikun
 * @date : 2025/2/12 下午3:31
 * @desc : Copyright © zanglikun.com
 */
public class FFXIAnnounce {

    // ENUM: Send to every character, in every zone, on every map process
    private static final byte MSG_CHAT_SERVMES = 6;

    // Message offset
    private static final int MESSAGE_OFFSET = 0x17;

    public static void main(String[] args) {
        String message = "";
        if (args.length > 0){
            message = args[0];
        }else {
            message = "GM: Hello!";
        }
        sendServerMessage(message);
    }


    private static void sendServerMessage(String msg) {
        System.out.println("Sending '" + msg + "'");

        try (ZContext context = new ZContext()) {
            Socket socket = context.createSocket(ZMQ.DEALER);
            socket.connect("tcp://127.0.0.1:54003");

            byte[] buffer = buildChatPacket(MSG_CHAT_SERVMES, true, (byte) 0, "", msg);
            socket.sendMore(ByteBuffer.allocate(1).put(MSG_CHAT_SERVMES).array());
            socket.send(new byte[0]); // Empty delimiter
            socket.send(buffer);
        }
    }

    private static byte[] buildChatPacket(byte msgType, boolean gmFlag, byte zone, String sender, String msg) {
        int buffSize = Math.min(236, MESSAGE_OFFSET + msg.length());
        ByteBuffer buffer = ByteBuffer.allocate(buffSize);

        buffer.put((byte) 0x17);
        buffer.put((byte) 0x82);
        buffer.put((byte) 0); // Reserved
        buffer.put((byte) 0); // Reserved

        buffer.put(4, msgType);

        buffer.put(5, (byte) (gmFlag ? 0x01 : 0x00));
        buffer.put(6, zone);

        // Set sender
        byte[] senderBytes = sender.getBytes(StandardCharsets.UTF_8);
        buffer.position(0x08);
        buffer.put(senderBytes);

        // Set message
        byte[] msgBytes = msg.getBytes(StandardCharsets.UTF_8);
        buffer.position(MESSAGE_OFFSET);
        buffer.put(msgBytes);

        return buffer.array();
    }
}
